home *** CD-ROM | disk | FTP | other *** search
- Path: gollum.kingston.net!usenet
- From: girard@haventree.com (Eugene Girard)
- Newsgroups: comp.lang.c++
- Subject: Re: Why Do I Use An Ampersand in Member Class Parameters?
- Date: Fri, 16 Feb 1996 17:33:25 GMT
- Organization: HavenTree Software, Limited
- Message-ID: <4g2im4$sv3@gollum.kingston.net>
- References: <4emnv2$n5o@alcor.usc.edu>
- NNTP-Posting-Host: buddy.haventree.com
- X-Newsreader: Forte Free Agent v0.55
-
- wawda@alcor.usc.edu (Abu Wawda) wrote:
-
- >I mean, I would understand if I parameter were a pointer to a Simple
- >class, but that is not the case, since I am not doing:
-
- >int Simple::operator += (const Simple ¶meter)
- >{
- > data += parameter->data;
- >}
-
- >Then why is there an amersand? I would appreciate any
- >suggestions. Thank you!
-
- Two possible answere (since I'm not sure which question you are
- asking...)
- Q1) Why do you use an ampersand in an assignment operator?
- A1) Because if you don't then a copy constructor will be called to
- pass the parameter. IE:
-
- Simple &Simple::operator+=( const Simple param)
- {
- data += param.data;
- return (*this);
- }
- would cause Simple's copy constructor to be called whenever you
- write something like:
- Simple x, y;
- x += y;
- Which would obviously be quite bad for complex classes.
-
- Q2) If foo( B &x) actually takes a pointer to x, then why can you
- refer to x.data instead of x->data inside of foo?
- A2) This is because references are special extensions to the
- language. If you want to, you can think of a reference parameter
- as adding a & before every variable passed in to the function, and
- adding an * before every reference to the variable inside of the
- function. (Of course, this is done invisibly to the programmer.)
- Thus,
- void Foo( X &d)
- { d.data += 10;}
- ...
- Foo( q);
- is effectively translated to
- void Foo( X *d)
- { (*d).data += 10;}
- ...
- Foo( &(q));
- when the compiler operates on it.
-
-
- --
- Eugene Girard, Programmer, HavenTree Software Limited
- HavenTree makes EasyFlow (Windows, DOS, MAC) and Nodemap (Windows, DOS)
- For more information, check out http://www.haventree.com
-
-